import sys
import os
import argparse

# 添加项目根目录到模块搜索路径
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
sys.path.insert(0, project_root)

# 现在可以正常导入 src 模块了
from src.core.file_utils import clean_path  # 导入路径清洗函数
from src.scripts.gui import main as gui_main
from src.api.openai_api import OpenAIClient
from src.config.settings import API_KEY, BASE_URL
from src.services.question_service import run_processing_pipeline # (添加这行)
from src.core.image_utils import process_image
from src.core.file_utils import write_answers_to_word

def main():
    parser = argparse.ArgumentParser(description='智能助手工具集')
    parser.add_argument('--no-gui', action='store_false', dest='gui', 
                       help='使用命令行模式（默认使用图形界面）')
    args = parser.parse_args()
    
    if args.gui:
        # 启动图形界面
        from src.scripts.gui import main as gui_main
        gui_main()
    else:
        # 命令行模式
        from src.api.openai_api import OpenAIClient
        from src.config.settings import API_KEY, BASE_URL
        from src.core.image_utils import process_image
        from src.core.file_utils import write_answers_to_word
        
        client = OpenAIClient(api_key=API_KEY, base_url=BASE_URL)
        print("请选择处理类型：")
        print("1. 处理 Word 文档")
        print("2. 处理图片")
        choice = input("请输入选项（1 或 2）: ")
        
        if choice == "1":
            # 获取并清洗输入路径
            in_path = clean_path(input("请输入 Word 文档路径: "))
            out_path = clean_path(input("请输入输出 Word 文档路径: "))

            run_processing_pipeline(in_path, out_path, client)

            print(f"文档处理完成，结果已保存到 {out_path}")
        elif choice == "2":
            # 获取并清洗输入路径
            img_path = clean_path(input("请输入图片文件路径: "))
            out_path = clean_path(input("请输入输出 Word 文档路径: "))
            
            # 检查文件是否存在
            if not os.path.exists(img_path):
                print(f"错误：文件不存在: {img_path}")
                return
            
            # 处理图片
            res = process_image(img_path, client)
            print("图片处理结果：")
            print(res)
            
            # 保存结果
            write_answers_to_word([res], out_path)
            print(f"图片分析结果已保存到 {out_path}")
        else:
            print("无效选项，请重新运行程序并选择有效选项")

if __name__ == "__main__":
    main()